package com.tanger.auth.auth;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import org.springframework.security.oauth2.common.OAuth2AccessToken;

import java.io.IOException;
import java.util.Map;

/***
 *   封装 /auth/token的返回内容格式
 * */
public class ResponseSerializer extends StdSerializer<Response> {
    public ResponseSerializer() {
        super(Response.class);
    }

    @Override
    public void serialize(Response value, JsonGenerator gen, SerializerProvider provider) throws IOException {
        OAuth2AccessToken oAuth2AccessToken = (OAuth2AccessToken) value.getData();
        Map<String,Object> userMap = value.getResultMap();
        gen.writeStartObject();
        gen.writeStringField("status", value.getErrorcode());
        gen.writeStringField("message", value.getValue());
        if(value.getErrorcode().equals("200")){
            gen.writeObjectFieldStart("data");
            gen.writeStringField("token", oAuth2AccessToken.getValue());
            gen.writeStringField("tokenType", oAuth2AccessToken.getTokenType());
            gen.writeStringField("refreshToken", oAuth2AccessToken.getRefreshToken()!=null?oAuth2AccessToken.getRefreshToken().getValue():"");
            String roleCode = "superAdmin";
            gen.writeStringField("roleCode",roleCode);
            gen.writeStringField("roleName","");
            gen.writeStringField("avatar","");
            gen.writeStringField("userId",userMap.get("id").toString());
            gen.writeStringField("userName",userMap.get("name").toString());
            gen.writeStringField("phone",userMap.get("mobile").toString());
            gen.writeObjectField("permissions",userMap.get("permissions"));//权限
            gen.writeNumberField("expiredTime",oAuth2AccessToken.getExpiresIn());//System.currentTimeMillis() +
        }
        gen.writeEndObject();
        gen.writeEndObject();
    }
}
